import { app, BrowserWindow, ipcMain, dialog, shell, OpenExternalOptions } from 'electron'
import { createContextMenu } from '@/main/buildWindow'

async function handleFileOpen(): Promise<string[]> {
  const { canceled, filePaths } = await dialog.showOpenDialog({
    properties: ['openFile', 'multiSelections'],// 配置对话框行为
    defaultPath: app.getPath('documents'), // 默认打开用户文档目录
    title: '请选择文件',
  })
  if (!canceled) {
    console.log("🚀 ~ handleFileOpen ~ filePaths:", filePaths)
    return filePaths
  }
  return []
}
const ipcEventListener = () => {
  //  IPC传统的事件监听 ipcRenderer.send 或 ipcRenderer.sendSync 返回event.reply
  ipcMain.on('set-title', (event, title) => {
    const win = BrowserWindow.fromWebContents(event.sender)
    let msg = '修改标题为{' + title + '}成功'
    if (win) {
      win.setTitle(title)
    } else {
      console.error('Attempted to set title on a closed or non-existent window.')
      msg = '设置标题失败'
    }
    event.reply('set-title-reply', msg)
  })

  ipcMain.handle("dialog:openFile", handleFileOpen)


  // 示例 IPC 双向通信 监听handle事件
  ipcMain.handle('get-platform', () => process.platform)

  // 监听显示菜单的事件
  ipcMain.on('show-context-menu', (event) => {
    const win = BrowserWindow.fromWebContents(event.sender);
    if (win) {
      createContextMenu(win)
    }
  });

  ipcMain.on('show-item-in-folder', (_event, path) => {
    shell.showItemInFolder(path)
  })


  ipcMain.on('open_external', (_event, url, options?: OpenExternalOptions) => {
    shell.openExternal(url, options)
  })

}


export { ipcEventListener }


